<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
server地址 :  <input id ="serveraddress" type="text" value="websocket"/><br/>
您的用户id :  <input id ="userId" type="text" /><br/>
<button onclick="initSocket()">连接</button><br/>
<button onclick="socketClose()">关闭连接</button>

=====================================================<br/>
消息发送对象 : <input id ="sendToUserId" type="text" /><br/>
消息 :  <input id ="message" type="text" /><br/>
<button onclick="send()">发送</button><br/>
=====================================================<br/>
连接状态 : <button onclick="clearConnectStatu()">清空</button><br/>
<div id="connectStatu"></div><br/>

=====================================================<br/>
收到消息 :<br/>
<div id="receivedMessage"></div><br/>
=====================================================<br/>
心跳 :<br/>
<div id="heartdiv"></div><br/>
<!--=====================================================<br/>-->
<!--<div>-->
    <!--session添加用户：<input type="text" id="suserId">-->
    <!--<button onclick="addSessionUserId()">添加</button>-->
<!--</div>-->
</body>

<script src="/js/jquery.min.js"></script>
<!--<script>-->
<!--$.post("/addsession/"+$("#userId").val(),function (data) {-->
    <!--alert(data);-->
<!--})-->
<!--</script>-->
<script type="text/javascript">
    

    
    var heartflag = false;
    var webSocket = null;
    var tryTime = 0;
    $(function () {

//        initSocket();
        window.onbeforeunload = function () {

        };
    });


    function socketClose() {
        webSocket.close();
    }

    /**
     * 初始化websocket，建立连接
     */
    function initSocket() {
        var serveraddress = $("#serveraddress").val();
        var userId = $("#userId").val();

        if (!window.WebSocket) {
            $("#connectStatu").append(getNowFormatDate()+"  您的浏览器不支持ws<br/>");
            return false;
        }

        webSocket = new WebSocket("ws://localhost:8888/"+serveraddress+"/"+userId);

        // 收到服务端消息
        webSocket.onmessage = function (msg) {
//            if(msg.data == "&"){
//
//            }else{
                $("#receivedMessage").append(getNowFormatDate()+"  收到消息 : "+msg.data+"<br/>");
//            }
        };

        // 异常
        webSocket.onerror = function (event) {
            heartflag = false;
            $("#connectStatu").append(getNowFormatDate()+"  异常<br/>");
        };

        // 建立连接
        webSocket.onopen = function (event) {
            heartflag = true;
//            heart();
            $("#connectStatu").append(getNowFormatDate()+"  建立连接成功<br/>");
            tryTime = 0;
        };

        // 断线重连
        webSocket.onclose = function () {
//            heartflag = false;
//            // 重试10次，每次之间间隔10秒
//            if (tryTime < 2) {
//                setTimeout(function () {
//                    webSocket = null;
//                    tryTime++;
//                    initSocket();
//                    $("#connectStatu").append( getNowFormatDate()+"  第"+tryTime+"次重连<br/>");
//                }, 3*1000);
//            } else {
//                alert("重连失败.");
//            }
            alert("关闭连接")
        };

    }

    function send(){
        var messageContent = $("#message").val();
        var messageUserId = $('#sendToUserId').val();
        var message = {
            "userId":messageUserId,
            "message":messageContent
        };
        console.log(message);
        webSocket.send(JSON.stringify(message));
    }

    function clearConnectStatu(){
        $("#connectStatu").empty();
    }

    function getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var seperator2 = ":";
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
            + " " + date.getHours() + seperator2 + date.getMinutes()
            + seperator2 + date.getSeconds();
        return currentdate;
    }

    function heart() {
        if (heartflag){
            webSocket.send("&");
            $("#heartdiv").append(getNowFormatDate()+"  心跳 <br/>");
        }
        setTimeout("heart()", 10*60*1000);

    }
</script>


</html>